package com.TexasHoldem.ServerData.Quest;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import net.sf.json.JSONObject;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.TexasHoldem.RpcInterface.rpc.TexasHoldemService;
import com.TexasHoldem.RpcInterface.rpc.TexasHoldemService.QuestList.Builder;
import com.TexasHoldem.ServerData.PokerPlayer;
import com.TexasHoldem.db.TexasHoldemDB;

/**
 * @author su
 * 玩牌获胜次数奖励
 */
public class PlayPokerQuest implements PokerQuest
{

	public Long id;
	// 保存获胜任务进度 任务目标次=>当前进度_完成状态
	public Map<Integer,String> winquestdata = new HashMap<Integer,String>();
	private Lock lock = new ReentrantLock();
	public PokerPlayer pokerplayer;
	@Override
	public void OnInit(PokerPlayer pokerplayer)
	{
		this.pokerplayer = pokerplayer;
		Integer questid = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerOnlineAwardQuest.class.getSimpleName()).getQuestid();
		// TODO Auto-generated method stub		
		Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
		QueryRunner qr = new QueryRunner();
		String sql = "select id,player_id,questdata from playerquest where player_id=? and questId=?";
	    try 
	    {
	    	List results = (List) qr.query(c,sql,new BeanListHandler(QuestBean.class),pokerplayer.getId(),questid);
	    	
	    	for (int i = 0; i < results.size(); i++) {
	    		QuestBean gb = (QuestBean) results.get(i);
	    		this.id = gb.getId();
	    		this.winquestdata.putAll(JSONObject.fromObject(gb.getQuestdata()));
            }
	    	
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
	    finally
	    {
	    	DbUtils.closeQuietly(c);
	    }
		
	}

	@Override
	public void OnQuestProcess()
	{
		if(pokerplayer.getStatistics().getLoginTime().get() == 0)
			return;
		
		try
		{
			lock.lock();
			
			
			// TODO Auto-generated method stub
			int wincount = (int)pokerplayer.getStatistics().getEveryday_win().get();
			if(wincount > 0)
			{
				for(QuestData qd:PokerQuestRule.getPokerQuestRule().getEvery_winquest())
				{
					if(winquestdata.containsKey(Integer.parseInt(qd.getWincount())))
					{
						Integer queststate = Integer.parseInt(winquestdata.get(Integer.parseInt(qd.getWincount())).split("_")[1]);
						
						if(queststate != QUEST_AWARED)
						{
							if(wincount >= Integer.parseInt(qd.getWincount()))
								winquestdata.put(Integer.parseInt(qd.getWincount()), String.format("%d_%d", wincount,QUEST_FINISH));
							else
								winquestdata.put(Integer.parseInt(qd.getWincount()), String.format("%d_%d", wincount,QUEST_UNFINISH));
						}
					}
					else
					{
						if(wincount >= Integer.parseInt(qd.getWincount()))
							winquestdata.put(Integer.parseInt(qd.getWincount()), String.format("%d_%d", wincount,QUEST_FINISH));
						else
							winquestdata.put(Integer.parseInt(qd.getWincount()), String.format("%d_%d", wincount,QUEST_UNFINISH));
					}
					
				}
				
			}
		}
		finally
		{
			lock.unlock();
		}
		
	}

	@Override
	public void OnFinish(int questId,String questAwardParam)
	{
		// TODO Auto-generated method stub
		QuestImpleMap ql = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayPokerQuest.class.getSimpleName());
		if(ql.getQuestid() != questId)
			return;
		try
		{
			lock.lock();
			if(winquestdata.containsKey(Integer.parseInt(questAwardParam)))
			{
				Integer wincount = Integer.parseInt(questAwardParam);
				Integer queststate = Integer.parseInt(winquestdata.get(Integer.parseInt(questAwardParam)).split("_")[1]);
				
				if(!queststate.equals(QUEST_AWARED))
				{
					for(QuestData qd:PokerQuestRule.getPokerQuestRule().getEvery_winquest())
					{
						
						if(Integer.parseInt(qd.getWincount()) == wincount)
						{
							pokerplayer.setYXB(pokerplayer.getYXB() + Integer.parseInt(qd.getAward()));
							winquestdata.put(wincount, String.format("%d_%d", wincount,QUEST_AWARED));
							break;
						}
					
					
					}
				}
			}
			
		}
		finally
		{
			lock.unlock();
		}
		
		
		
		
	}

	@Override
	public void OnSave()
	{
		// TODO Auto-generated method stub
		JSONObject js = new JSONObject();
		js.putAll(winquestdata);
		Integer questid = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayPokerQuest.class.getSimpleName()).getQuestid();
		if(id != null)
		{
			Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
			QueryRunner qr = new QueryRunner();
			String sql = "update playerquest set player_id=?,questdata=?,questId=? where id=?";
		    try {
		        qr.update(c, sql, pokerplayer.getId(),js.toString(),questid,this.id);
		    } catch (SQLException e) {
		        e.printStackTrace();
		    }
		    finally
		    {
		    	DbUtils.closeQuietly(c);
		    }
		}
		else
		{
			Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
			QueryRunner qr = new QueryRunner();
			String sql = "insert into playerquest (player_id, questdata,questId) values (?,?,?)";
		    try {
		    	qr.update(c, sql, pokerplayer.getId(),js.toString(),questid);
		        BigInteger newId = (BigInteger) qr.query(c, "select last_insert_id()", new ScalarHandler<BigInteger>(1));
		        this.id = newId.longValue();
		    } catch (SQLException e) {
		        e.printStackTrace();
		    }
		    finally
		    {
		    	DbUtils.closeQuietly(c);
		    }
		}
	}
	
	@Override
	public void toQuest(Builder qb)
	{
		// TODO Auto-generated method stub
		Set<Integer> addquest = new HashSet<Integer>();
		QuestImpleMap ql = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayPokerQuest.class.getSimpleName());
		for(QuestData qd:PokerQuestRule.getPokerQuestRule().getEvery_winquest())
		{
			
			if(!this.winquestdata.containsKey((Integer.parseInt(qd.getWincount()))))
				continue;
			TexasHoldemService.Quest.Builder quest = TexasHoldemService.Quest.newBuilder();
			
			
			Integer cur = Integer.parseInt(this.winquestdata.get(Integer.parseInt(qd.getWincount())).split("_")[0]); 
			Integer queststate = Integer.parseInt(this.winquestdata.get(Integer.parseInt(qd.getWincount())).split("_")[1]);
			
			if(queststate.equals(QUEST_FINISH))
			{
				quest.setAward(Integer.parseInt(qd.getAward()));
				quest.setCur(Integer.parseInt(qd.getWincount()));
				quest.setEnd(Integer.parseInt(qd.getWincount()));
				quest.setName(ql.getDesc()+qd.getWincount());
				quest.setQuestId(ql.getQuestid());
				quest.setQuestAwardparam(qd.getWincount());
				qb.addQuests(quest);
				addquest.add(Integer.parseInt(qd.getWincount()));
				
			}
		}
		
		if(qb.getQuestsCount() < 2)
		{
			

			for(QuestData qd:PokerQuestRule.getPokerQuestRule().getEvery_winquest())
			{
				
				if(!this.winquestdata.containsKey((Integer.parseInt(qd.getWincount()))))
					continue;
				if(addquest.contains(Integer.parseInt(qd.getWincount())))
					continue;
				
				if(qb.getQuestsCount() >= 2)
					break;
				TexasHoldemService.Quest.Builder quest = TexasHoldemService.Quest.newBuilder();
				
				
				Integer cur = Integer.parseInt(this.winquestdata.get(Integer.parseInt(qd.getWincount())).split("_")[0]); 
				Integer queststate = Integer.parseInt(this.winquestdata.get(Integer.parseInt(qd.getWincount())).split("_")[1]);
				
				if(!queststate.equals(QUEST_AWARED))
				{
					quest.setAward(Integer.parseInt(qd.getAward()));
					quest.setCur(cur);
					quest.setEnd(Integer.parseInt(qd.getWincount()));
					quest.setName(ql.getDesc()+qd.getWincount());
					quest.setQuestId(ql.getQuestid());
					quest.setQuestAwardparam(qd.getWincount());
					qb.addQuests(quest);
					
				}
			}
				
				
			
		}
	}


}
